package cn.zhz.controller;

import cn.zhz.entity.Provider;
import cn.zhz.service.provider.ProviderService;
import cn.zhz.tools.Constants;
import cn.zhz.tools.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("provider")
public class ProviderController {
    private Logger logger = Logger.getLogger(ProviderController.class);

    @Resource
    private ProviderService providerService;

    @RequestMapping(value = "list.html", method = RequestMethod.GET)
    public String getProviderList(Model model,
                                  @RequestParam(value = "queryProCode", required = false) String queryProCode,
                                  @RequestParam(value = "queryProName", required = false) String queryProName,
                                  @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        logger.info("getProviderList ---> queryProCode：" + queryProCode);
        logger.info("getProviderList ---> queryProName：" + queryProName);
        logger.info("getProviderList ---> pageIndex：" + pageIndex);

        List<Provider> providerList = null;
        //设置页码容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryProCode == null) {
            queryProCode = "";
        }
        if (queryProName == null) {
            queryProName = "";
        }
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量
        int totalCount = providerService.getProviderCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        providerList = providerService.getProviderList(queryProName, queryProCode, currentPageNo, pageSize);
        model.addAttribute("providerList", providerList);
        model.addAttribute("queryProName", queryProName);
        model.addAttribute("queryProCode", queryProCode);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "/provider/providerlist";
    }

    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    public String addProvider(@ModelAttribute("provider") Provider provider) {
        return "/provider/provideradd";
    }

    @RequestMapping(value = "/addSave.html", method = RequestMethod.POST)
    public String addSave(@Valid Provider provider, BindingResult bindingResult, HttpServletRequest request,
                          @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        /*if (bindingResult.hasErrors()) {
            logger.debug("add provider validated has error =====");
            return "provider/provideradd";
        }*/

        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("uploadFile path ============== > " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("uploadFile oldFileName ============== > " + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                logger.debug("uploadFile prefix============> " + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============> " + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPicPath = fileName;
                    } else if (i == 1) {
                        orgCodePicPath = fileName;
                    }
                    logger.debug("companyLicPicPath: " + companyLicPicPath);
                    logger.debug("orgCodePicPath: " + orgCodePicPath);

                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            provider.setCreatedBy(1);
            provider.setCreationDate(new Date());
            provider.setCompanyLicPicPath(companyLicPicPath);
            provider.setOrgCodePicPath(orgCodePicPath);
            if (providerService.add(provider)) {
                return "redirect:/provider/list.html";
            }
        }
        return "provider/provideradd";
    }

    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(@PathVariable String id, Model model) {
        Provider provider = providerService.getProviderById(id);
        model.addAttribute(provider);
        return "/provider/providerview";
    }

    @RequestMapping(value = "/modify.html/{id}", method = RequestMethod.GET)
    public String modify(@PathVariable String id, Model model) {
        Provider provider = providerService.getProviderById(id);
        model.addAttribute(provider);
        return "provider/providermodify";
    }

    @RequestMapping(value = "/modifySave.html", method = RequestMethod.POST)
    public String modifyProvider(Provider provider) {
        provider.setModifyBy(provider.getModifyBy() == null ? 1 : provider.getModifyBy() + 1);
        provider.setModifyDate(new Date());
        if (providerService.modify(provider)) {
            return "redirect:/provider/list.html";
        }
        return "provider/providermodify";
    }
}
